package com.cloud.business.exception;

import com.cloud.business.enums.ResultEnum;
import com.cloud.business.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@RestControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResultVO handleException(Exception e){
        log.error(e.getMessage(), e);
        return ResultVO.error();
    }

    /*
     * 捕捉异常HttpRequestMethodNotSupportedException
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResultVO handleValidException(HttpRequestMethodNotSupportedException exception, HttpServletRequest req) {
        log.error("HttpRequestMethodNotSupportedException{},{},{}",
                exception.getClass(),
                exception.getMessage(),
                req.getRequestURL().toString());
        return ResultVO.msg(ResultEnum.UNSUPPORTED_REQUEST_METHOD);
    }

    /**
     * 处理 HTTP 404 错误
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResultVO handleNotFound(HttpServletRequest req, Exception ex) {
        return ResultVO.msg(HttpStatus.NOT_FOUND.value(), "无该资源: " + req.getRequestURI());
    }

}
